/*
* dataview 私有方法
* */
import utilVuex from '../../utilVuex.js'

const dvFunPrivate = {

  //是否可以多选
  checkMethod({row}) {
    if (this.isEditPlaceholderRow(row)) return false
    if (!this.propDisableCheck) return true
    if (eval(this.propDisableCheck)) return false
    return true
  },
  isCustomCol(colName) {
    const extraFlag = this.propExtraColumns && this.propExtraColumns.findIndex((item) => item.name === colName) > -1
    const customFlag = this.propCustomCols && this.propCustomCols.indexOf(colName) > -1
    return extraFlag || customFlag
  },
  // 编辑界面事件注册
  viewFormeventRegister(config) {
    this.viewFormEvents = config
  },
  handleViewFormAddButton(button) {
    const find = this.viewFormButtons.find((item) => item.key === button.key)
    if (!find) {
      this.viewFormButtons.push(button)
    }
  },
  // 选择流程节点
  handleChangeFlowNode({data}) {
    this.flowNodeValue = data.flowNodeValue
    localStorage.setItem('dataview_flowNodeValue_' + this.propViewKey, data.flowNodeValue)
    this.tablePage.currentPage = 1
    this.fetchData()
    this.$emit('flow-change', this.flowNodeValue)
  },
  // 编辑界面回传数据
  handleViewFormDataCallback(data) {
    this.viewFormData = data
  },
  // 编辑界面关闭
  handleDetailClose(done) {
    const {beforeClose} = this.viewFormEvents
    if (!beforeClose || beforeClose()) {
      this.viewFormData = {}
      done()
    }
    //刷新网格数据
    this.fetchData(false, false, true)
  },
  // 鼠标离开时触发，根据是否选中 添加或者移除选中样式
  handleCellMouseleave(param) {
    let checked = this.$refs.tbMain.isCheckedByCheckboxRow(param.row)
    let trIndex = $(param.cell).closest('tr').index()
    let vxeGrid = $(param.cell).closest('.vxe-grid')
    if (checked) {
      vxeGrid.find('.vxe-table--body').each(function () {
        let tr = $(this).find('tr:eq(' + trIndex + ')')
        let checkBox = tr.find('.vxe-cell--checkbox')
        if (checkBox.hasClass('is--checked')) tr.addClass('row-check')
      })
    } else {
      vxeGrid.find('.vxe-table--body').each(function () {
        let tr = $(this).find('tr:eq(' + trIndex + ')')
        let checkBox = tr.find('.vxe-cell--checkbox')
        if (!checkBox.hasClass('is--checked')) tr.removeClass('row-check')
      })
    }
  },
  // 主界面按钮事件
  async handleButton(button) {
    if (!this._propBeforeClick(button, null , null)) {
      return
    }
    let pass = true
    //按钮点击前执行
    this.$emit('before-button-click', {
      btn: button,
      call: (passParam) => {
        if (pass != undefined) pass = passParam
      }
    })
    if (!pass) return

    if (this.beforeButtonClickAsync) {
      pass = await this.beforeButtonClickAsync(button)
      if (!pass) return
    }

    if (button.flagBatch == true) { //批量流程操作
      let valueIf = button.valueIf
      let valueTo = button.valueTo
      let valueIfTitle = button.valueIfTitle
      let title = button.title
      let checkRows = this.$refs.tbMain.getCheckboxRecords()
      if (!checkRows || checkRows.length < 1) {
        this.utilMessage.warning(`请选择需要${button.name}的记录`)
        return
      }
      checkRows = checkRows.filter(row => row.flowStatus == valueIf)

      if (!checkRows || checkRows.length < 1) {
        this.utilMessage.warning(`您所选择数据没有【${valueIfTitle}】的数据`)
        return
      }

      this.$confirm(`确认将所选择的【${checkRows.length}】张单据进行【${title}】么？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      }).then(() => {
        if (button.flagBatch2 && button.flagBatch2 == true) {
          this.flowChangeBatch2(button, checkRows)
        } else {
          this.flowChangeBatch1(button, checkRows)
        }
      }).catch(() => {
      })
      return
    }
    if (button.key.indexOf('flow_') > -1) {
      let flowNodeValue = button.key && (button.key + '').replace('flow_', '')
      this.handleChangeFlowNode({data: {flowNodeValue}})
      return
    }
    switch (button.key) {
    case 'vb-add':
      this.viewAdd()
      break
    case 'vb-refresh':
      this.fetchData()
      break
    case 'vb-delete':
      this.viewBatchDelete()
      break
    case 'vb-search':
      this.handleQueryClick()
      break
    case 'vb-reset':
      this.handleUserQueryReset()
      break
    case 'vb-toggle':
      this.toggleForm()
      break
    default:
      this.$emit('extra-button-click', {
        button,
        data: this.$refs.tbMain.getCheckboxRecords(),
        rows: this.rows0,
        userQuery: this.tableForm,
        extraButtonClickParam: this.propExtraButtonClickParam
      })
      this.$emit('btnClick', {
        button,
        data: this.$refs.tbMain.getCheckboxRecords(),
        rows: this.rows0,
        userQuery: this.tableForm,
        extraButtonClickParam: this.propExtraButtonClickParam
      })
    }
  },

  /**
   * @Description：前置点击方法
   * @Date 2024-04-11
   * @param button    按钮
   * @param formData  表单数据
   * @param rowData   行数据
  */
  _propBeforeClick(button, formData , rowData) {
    if (!this.propBeforeClick) {
      return true
    }
    return this.propBeforeClick(button, formData , rowData, this)
  },
  // 行按钮事件
  handleRowButton(button, index, row) {
    if (!this._propBeforeClick(button, null , row)) {
      return
    }
    switch (button.key) {
    case 'vrb-edit':
      this.rowEdit(row, false)
      break
    case 'vrb-view':{
      if (this.rowViewCustom){
        this.rowViewCustom(row)
        return
      }
      this.rowEdit(row, true)
      break
    }
    case 'vrb-delete':
      this.rowDelete(row)
      break
    case 'vrb-new-delete':
      this.newRowDelete(row)
      break
      /*case 'vrb-flow-log':
        this.rowFlowLog(row)
        break*/
    default:
      this.$emit('extra-button-click', {
        button,
        data: row,
        index,
        extraButtonClickParam: this.propExtraButtonClickParam
      })

      this.$emit('btnClick', {
        button,
        data: row,
        index,
        extraButtonClickParam: this.propExtraButtonClickParam
      })
    }
  },
  handleCommentDialogOpen() {
    this.$refs.attachment && this.$refs.attachment.clearFiles()
  },
  handleUploadSuccess(data) {
    this.$set(this.flowCommentForm, 'attachmentUrl', data.url)
  },
  // 当前页发生改变事件
  handlePageChange({currentPage, pageSize}) {
    this.tablePage.currentPage = currentPage
    this.tablePage.pageSize = pageSize

    localStorage.setItem('dataview_pagesize_' + this.propViewKey, pageSize)
    this.fetchData(true)
  },
  handleSortChange({data, column, property, order}) {
    if (!this.showPagination) return
    //if (!prop || column.sortable != 'custom') {
    this.orderField = property
    if (!this.orderType) {
      this.orderType = order
    } else {
      if (this.orderType == 'asc') {
        this.orderType = 'desc'
      } else {
        this.orderType = 'asc'
      }
    }

    this.userOrder = [{field: this.orderField, rule: this.orderType}]
    this.fetchData()
  },
  handleGridHeaderClick(column, event) {
    let {roleCodes = [], code} = this.utils.getCurrentUser()
    let show = false
    if (code == 'admin' || roleCodes.includes('admin') || this.utils.isAdmin()) {
      show = true
    }
    if (!event.ctrlKey && !event.metaKey) {
      return
    }

    if (column.type == 'header' && (process.env.NODE_ENV === 'development' || show)) {
      global.utils.openMenu('frame/data-view/list', {viewKey: this.propViewKey})
    }
  },
  // 重置用户查询条件
  handleUserQueryReset() {
    Object.keys(this.tableForm.data).forEach((key) => {
      if (Object.prototype.hasOwnProperty.call(this.tableForm.data, key)) {
        this.tableForm.data[key] = ''
      }
    })
    this.tableFormState = {}
    this.searchGroup = {}
    this.flowNodeValue = ''
    localStorage.removeItem('dataview_groupname_' + this.propViewKey)
    localStorage.removeItem('dataview_groupfield_' + this.propViewKey)
    //回调重置
    this.$emit('reset')
    this.fetchData()
  },
  // 主页面添加动作
  viewAdd() {
    this.addnew()
  },
  // 编辑界面添加动作
  viewFormAdd() {
    this.addnew()
  },
  // 编辑界面取消动作
  viewFormCancel() {
    this.$set(this, 'viewFormStatus', 'edit')
    this.$set(this, 'viewFormVisible', false)
  },
  // 将上传的验证函数包装成Promise
  validatePromise(validate) {
    return new Promise((resolve, reject) => {
      if (!validate) {
        resolve(true)
      }
      validate((valid) => {
        resolve(valid)
      })
    })
  },
  //重设字典值
  setEditDatas(key, value) {
    this.viewFormEditDatas[key] = value
  },
  //设置行编辑数据查询的条件
  setEditQueries(key, value) {
    this.editQueries[key] = value
  },
  //设置行编辑数据查询的条件
  setEditUserParam(key, value) {
    this.editUserParam[key] = value
  },
  setEditColumns(key, value) {
    this.viewFormEditColumns[key] = value
  },
  // 编辑界面保存动作，流程提交动作
  async viewFormSave(isFlowAction, call) {
    this.flagSuccessSave = false
    this.isRefreshCurrentRow = true

    const {beforeSave, afterSave, validate, beforeFlow, afterMove} = this.viewFormEvents
    if (validate) {
      let validateResult = false
      if (this.propIsTdesign && this.propIsTdesign == true) { //兼容tdesign
        validateResult = await validate()
        if (validateResult) {
          let isFail = false
          Object.keys(validateResult).forEach(key => {
            let arr = validateResult[key]
            if (!isFail && arr && arr.length > 0 && arr.findIndex(tmp => tmp.result == false) != -1) {
              isFail = true
            }
          })
          if (isFail) {
            return {code: 1001, msg: '验证未通过'}
          }
        }
      } else {
        validateResult = await this.validatePromise(validate)
        if (!validateResult) {
          return {code: 1001, msg: '验证未通过'}
        }
      }
      console.log('validateResult', validateResult)
    }
    if (beforeSave && !beforeSave()) {
      return {code: 1002, msg: '保存前检查未通过'}
    }
    if (isFlowAction && beforeFlow && !beforeFlow()) {
      return {code: 1003, msg: '流程检查未通过'}
    }
    let params = {}
    // 视图保存采用纯文本传输的方式，此处就是兼容这个操作
    if (this.propIsPostString) {
      params = {contents: JSON.stringify(this.viewFormData)}
    } else {
      params = this.viewFormData
      //追加拦截器需要使用的参数
      params = this.utils.appendParamForInterceptor(this, 'dataviewsave', params)
      if (!this.utilDataview.beforeSave(this, params)) return
    }
    console.log('this.viewFormData', this.viewFormData)
    this.utilVue.loadShow(true)
    try {
      const response = await this.$ajax.post(this.saveEntry, params)
      this.flagSuccessSave = response.success
      if (!response.success) {
        this.utilVue.loadHide()
        return response
      }
      this.utilVue.loadHide()
      this.utilMessage.success(response.msg)

      //this.$set(this, 'viewFormData', global.utils.jsonClone(response.data))
      if (!this.viewFormData[this.primaryKey]) {
        this.$set(this.viewFormData, this.primaryKey, response.data[this.primaryKey])
      }
      Object.keys(response.data).forEach(key => {
        this.$set(this.viewFormData, key, response.data[key])
      })
      if (call) {
        call()
      }

      setTimeout(() => {
        this.isRefreshCurrentRow = false
        this.$emit('afterTableDataChange')
      }, 3000)
    } catch (e) {
      this.utilVue.loadHide()
    }
    // this.refreshViewGrid(this.viewFormData[this.primaryKey], isFlowAction)
    //this.fetchData() //保存不需要刷新数据
    // 按保存按钮，全部触发afterMove事件
    let cursorChange = false
    if (this.viewFormStatus == 'addnew') {
      cursorChange = true
      this.$set(this, 'viewFormStatus', 'edit')
    }
    afterMove && afterMove(this.viewFormData, this.propInitData, this.viewFormStatus, cursorChange)
    afterSave && afterSave()
    if (this.flow && this.flowNodes.length > 0) { //如果是流程节点，刷新
      this.ocRefreshCurrentRow()
    }
    // 回调父界面事件
    this.$emit('after-save', this.viewFormStatus, this.viewFormData)
    return {code: 0, msg: '保存完成'}
  },
  // 保存完毕后刷新网格内容id
  refreshViewGrid(id, isFlowAction) {
    // 如果是流程改变，直接从网格中移除
    if (isFlowAction) {
      this.updateGridRow(id)
      this.viewFormVisible = false
      return
    }
    let wrapper = this.$newWrapper().eq(this.primaryKey, id)
    // const qString = `${this.primaryKey}=\'${id}\'`
    const qString = JSON.stringify(wrapper.queryConditions)
    const params = {
      queryString: qString,
      currentPage: 1,
      rowsPerPage: 1,
    }
    this.$ajax.get(this.listEntry, {params}).then((response) => {
      if (response.code == 0) {
        const record = response.data
        this.updateGridRow(id, record[0])
      }
    })
  },
  // 更新网格中一条数据,并将更新的数据置顶;不传newRow，表示单纯移除
  updateGridRow(id, newRow) {
    this.rows0.map((item, index) => {
      if (item[this.primaryKey] == id) {
        this.rows0.splice(index, 1)
        return true
      }
    })
    if (newRow) {
      this.rows0.unshift(newRow)
    }
    this.rows = global.utils.jsonClone(this.rows0)
    this.handlePageSearch()
  },
  // 编辑界面关闭动作
  viewFormClose() {
    this.formHide()
    this.handleDetailClose(() => {
      this.$set(this, 'viewFormStatus', 'edit')
      this.viewFormVisible = false
    })
  },
  // 编辑界面删除动作
  viewFormDelete() {
    const {beforeDelete, afterDelete} = this.viewFormEvents
    this.deleteAction(this.viewFormData, beforeDelete, afterDelete)
  },
  //新增行删除----还没有保存至数据库
  newRowDelete(row, index) {
    this.rows.splice(index, 1)
    this.$refs.tbMain.loadData(this.rows)
    this.fetchData()
  },
  // 行内按钮删除动作
  rowDelete(row) {
    this.deleteAction(row, null, null)
  },
  // 通用删除功能
  async deleteAction(row, beforeDelete, afterDelete) {
    let that = this
    // 删除前的回调
    if (beforeDelete && !beforeDelete()) {
      return {code: 1001, msg: '删除前检查未通过'}
    }
    // 同步等待结果
    const prompt = this.deletePrompt || '此操作将永久删除该条记录，是否继续?'
    const result = await this.$confirm(prompt)
    console.log('result', result)
    if (!result) {
      return {code: 1002, msg: '删除被取消'}
    }
    // 物理删除
    let params = {
      ids: [row[this.primaryKey]],
    }
    //追加拦截器需要使用的参数
    params = this.utils.appendParamForInterceptor(this, 'dataviewdelete', params, [row])

    this.utilVue.loadShow(true)
    const response = await this.$ajax.delete(this.deleteEntry, {data: params})
    if (response.code == 0) {
      // 删除后回调
      afterDelete && afterDelete()
      this.$emit('after-delete', row)
      // 界面移除
      this.rows0.map((item, index) => {
        if (item[this.primaryKey] === row[this.primaryKey]) {
          this.rows0.splice(index, 1)
        }
      })
      this.rows.map((item, index) => {
        if (item[this.primaryKey] === row[this.primaryKey]) {
          this.rows.splice(index, 1)
        }
      })
      this.currentRow = {}
      that.propParentPage && that.propParentPage.$emit('refresh-row')

      // 关闭界面
      this.viewFormClose()
      this.utilMessage.success('删除成功', 500)
      setTimeout(() => {
        this.insertFirst()
      }, 2000)
      this.$emit('afterTableDataChange')
    }
    this.utilVue.loadHide()
  },
  // 移除行，不调用接口
  removeRows(data, noMsg) {
    if (data instanceof Array) {
      // 批量移除
      if (data && data.length > 0) {
        this.rows0 = this.rows0.filter(item => !data.some(row => item[this.primaryKey] === row[this.primaryKey]))
        this.rows = this.rows.filter(item => !data.some(row => item[this.primaryKey] === row[this.primaryKey]))
      }
    } else {
      // 单行移除
      const row = data
      if (row && row[this.primaryKey]) {
        this.rows0 = this.rows0.filter(item => !item[this.primaryKey] === row[this.primaryKey])
        this.rows = this.rows.filter(item => !item[this.primaryKey] === row[this.primaryKey])
      }
    }

    this.rows0 = [...this.rows]
    this.$refs.tbMain.loadData(this.rows)
    noMsg || this.utilMessage.success('删除成功', 500)
    this.utilVue.loadHide()
  },
  // 批量删除
  viewBatchDelete() {
    let selectedRows = this.$refs.tbMain.getCheckboxRecords()
    if (selectedRows.length < 1) {
      selectedRows = this.currentRow[this.primaryKey] ? [this.currentRow] : []
    }
    if (selectedRows.length < 1) {
      global.utilMessage.alertFail('至少选择一条要删除的记录！')
      return
    }
    let that = this
    this.utilMessage.confirm(`确定要删除选中的${selectedRows.length}条记录吗？`, () => {
      this.utilVue.loadShow(true)
      const ids = []
      selectedRows.forEach((item) => {
        ids.push(item[this.primaryKey])
      })

      let params = {ids}
      //追加拦截器需要使用的参数
      params = this.utils.appendParamForInterceptor(this, 'dataviewdelete', params, selectedRows)
      this.$ajax
        .delete(this.deleteEntry, {
          data: params,
        })
        .then((response) => {
          if (response.code == 0) {
            that.fetchData()
            that.propParentPage && that.propParentPage.$emit('refresh-row')
            this.$emit('after-delete')
            setTimeout(() => {
              this.$emit('afterTableDataChange')
            }, 500)
          }
          //异常ajax已统一处理
          this.utilVue.loadHide()
          setTimeout(() => {
            this.insertFirst(true)
          }, 500)
        })
    })
  },
  // 生成查询条件功能
  generateQuery(isByStru, paramsOld) {
    let queryString = ''
    let userString = ''
    let field = ''
    let queryConditions = []

    let queryWrapper = this.$newWrapper()

    // 拼接初始条件

    if (this.propPreQueryWrapper) {
      queryConditions.push(...this.propPreQueryWrapper.queryConditions)
    }
    //拼接部门
    let userInfo = this.utils.getCurrentUser()
    let dataFilterFieldHit = this.dataFilterField
    dataFilterFieldHit = this.strings.defaultIfBlank(dataFilterFieldHit, this.dataFilterType)
    if (!this.strings.isBlank(this.dataFilterType) && !userInfo.admin && !userInfo.deptDataAll) { //非管理员，不能查看全部部门信息的
      if (this.dataFilterType == 'deptId') {
        if (this.formConfig.columns.filter(column => column.name == dataFilterFieldHit).length < 1) {
          queryWrapper.eq('1', '0')
          this.utilMessage.error('权限过滤失败，列表中未包含指定字段：' + dataFilterFieldHit)
          return JSON.stringify(queryWrapper.queryConditions)
        }
        queryWrapper.eq(dataFilterFieldHit, userInfo.deptId)
      } else if (this.dataFilterType == 'creator') {
        if (this.formConfig.columns.filter(column => column.name == dataFilterFieldHit).length < 1) {
          queryWrapper.eq('1', '0')
          this.utilMessage.error('权限过滤失败，列表中未包含指定字段：' + dataFilterFieldHit)
          return JSON.stringify(queryWrapper.queryConditions)
        }

        queryWrapper.eq(dataFilterFieldHit, userInfo.code)
      } else if (this.dataFilterType == 'warehouseId' || this.dataFilterType == 'fromWarehouseId') {
        if (this.formConfig.columns.filter(column => column.name == dataFilterFieldHit).length < 1) {
          queryWrapper.eq('1', '0')
          this.utilMessage.error('权限过滤失败，列表中未包含指定字段：' + dataFilterFieldHit)
          return JSON.stringify(queryWrapper.queryConditions)
        }
        queryWrapper.eq(dataFilterFieldHit, this.utils.getCurrentWarehouse().id)
      } else if (this.dataFilterType == 'warehouseDeptId') {
        dataFilterFieldHit = this.strings.defaultIfBlank(this.dataFilterField, 'deptId')
        if (this.formConfig.columns.filter(column => column.name == dataFilterFieldHit) < 1) {
          queryWrapper.eq('1', '0')
          this.utilMessage.error('权限过滤失败，列表中未包含指定字段：' + dataFilterFieldHit)
          return JSON.stringify(queryWrapper.queryConditions)
        }
        queryWrapper.eq(dataFilterFieldHit, this.utils.getCurrentWarehouse().deptId)
      } else if (this.dataFilterType == 'userDeptId') { //关联科室
        dataFilterFieldHit = this.strings.defaultIfBlank(this.dataFilterField, 'deptId')
        if (this.formConfig.columns.filter(column => column.name == dataFilterFieldHit) < 1) {
          queryWrapper.eq('1', '0')
          this.utilMessage.error('权限过滤失败，列表中未包含指定字段：' + dataFilterFieldHit)
          return JSON.stringify(queryWrapper.queryConditions)
        }
        queryWrapper.in(dataFilterFieldHit, userInfo.deptIds)
      } else if (this.dataFilterType == 'deptIdAdmin' && !userInfo.deptDataAll) { // 查看全院科室数据,否则看自己的拥有科室
        dataFilterFieldHit = this.strings.defaultIfBlank(this.dataFilterField, 'deptId')
        if (this.formConfig.columns.filter(column => column.name == dataFilterFieldHit) < 1) {
          queryWrapper.eq('1', '0')
          this.utilMessage.error('权限过滤失败，列表中未包含指定字段：' + dataFilterFieldHit)
          return JSON.stringify(queryWrapper.queryConditions)
        }
        queryWrapper.in(dataFilterFieldHit, userInfo.deptIds)
      } else if (this.dataFilterType == 'userDeptIdAndOr' && !userInfo.deptDataAll) { // 字段包含dept_id,登录人所在科室及所关联仓库科室
        dataFilterFieldHit = this.strings.defaultIfBlank(this.dataFilterField, 'DEPTID')
        let deptIdColumns = this.formConfig.columns.filter(column => column.name.toUpperCase().indexOf(dataFilterFieldHit.toUpperCase()) != -1)
        if (!deptIdColumns || deptIdColumns.length < 1) {
          queryWrapper.eq('1', '0')
          this.utilMessage.error('权限过滤失败，列表中未包含DEPTID字段：')
          return JSON.stringify(queryWrapper.queryConditions)
        }
        let queryWrapperAnd = this.$newWrapper()
        deptIdColumns.forEach(col => queryWrapperAnd.in(col.name, userInfo.deptIds))
        queryWrapper.andOrIn('and_or_in', JSON.stringify(queryWrapperAnd.queryConditions))
      }
    }

    // 拼接用户查询条件
    let that = this
    this.tableForm && Object.keys(this.tableForm.data).forEach((key) => {
      if (Object.prototype.hasOwnProperty.call(this.tableForm.data, key)) {
        let value = that.tableForm.data[key]
        if (value) value = this.strings.trimrl(value)
        if (that.strings.isBlank(value) && that.strings.isBlank(that.tableForm.data[key + '1'])) {
          return
        }
        if (key == that.fullSearchKey) {
          that.fullSearchFields.forEach(field => queryWrapper.orlike(field, value))
          return
        }
        let item = that.userQuery.filter(q => q.name == key)[0]
        if (!item) {
          return
        }
        if (item.queryType === 'numberArea') {
          let value1 = that.tableForm.data[key + '1']
          if (!value) value = 0
          if (!value1 || value1 == 0) value1 = 999999999

          queryWrapper.between(key, [value, value1])
        } else if (item.queryType === 'dateArea') {
          let value1 = that.tableForm.data[key + '1']

          //开始日期没有，则默认为 1970-01-01
          //结束日期没有，则默认为 2099-12-12，时分秒 固定为 23:59:59
          if (!value) value = '1970-01-01'
          if (!value1) value1 = '2099-12-12'

          let datePattern = 'yyyy-MM-dd'
          if (item.datePattern && item.datePattern == 'yyyy-MM-dd HH:mm:ss') datePattern = 'yyyy-MM-dd HH:mm:ss'
          value = this.dates.toDate(value, datePattern)
          value1 = this.dates.toDate(value1, datePattern)

          if (datePattern == 'yyyy-MM-dd') {
            value += ' 00:00:00'
            value1 += ' 23:59:59'
          }
          if (value > value1) {
            this.utilMessage.warning(`${item.title}开始日期不能大于结束日期`)
            queryWrapper.ne(1, 1)
            return
          }
          queryWrapper.between(key, [value, value1])
        } else if (item.queryType === 'select') {
          let options = []
          if (this.strings.isNotBlank(item.sourceVuex)) {  //从状态管理里面获取
            options = utilVuex[item.sourceVuex]()
          } else {
            options = item.dict ? this.utils.getDictDataList(item.dict, this) : this.viewFormDictionaries[item.name] //数据源
          }
          if (options && options.length > 0) {
            let dictListFilter = options.filter(dict => dict.label == value)
            if (dictListFilter != null && dictListFilter.length > 0) value = options.filter(dict => dict.label == value)[0].value
          }
          queryWrapper.eq(this.strings.defaultIfBlank(item.selectQueryField, key), value)
        } else {
          queryWrapper.like(key, value)
        }
      }
    })
    // 拼接流程条件
    if (this.baseColumns.findIndex(ob => ob.name == 'flowStatus') != -1 && this.flow.fieldName && this.strings.isNotBlank(this.flowNodeValue)) {
      queryWrapper.eq(this.flow.fieldName, this.flowNodeValue)
    }
    //拼接流程节点
    if (this.baseColumns.findIndex(ob => ob.name == 'flowStatus') != -1 && this.flowNodes && this.flowNodes.length > 0) {
      this.flowNodes.forEach(flow => {
        // 若指定了权限，并且没有指定everyone
        let {roleCodes = [], code, admin} = this.utils.getCurrentUser()
        if (code != 'admin' && !admin && this.strings.isNotBlank(flow.roleCodes) && flow.roleCodes.indexOf(this.roleEveryone) == -1) {
          let isHave = false
          flow.roleCodes.forEach(flowRoleCode => {
            if (roleCodes.includes(flowRoleCode)) {
              isHave = true
            }
          })
          if (!isHave) {
            queryWrapper.ne('flowStatus', flow.value)
          }
        }
      })
    }
    //拼接分组过滤条件
    if (this.searchGroup) {
      Object.keys(this.searchGroup).forEach(name => {
        if (this.searchGroup[name] && this.searchGroup[name].length > 0) {
          //该字段使用like
          if (this.columnsMap[name] && this.columnsMap[name].queryLike) {
            for (let valgroup in this.searchGroup[name]) {
              queryWrapper.like(name, valgroup)
            }
          } else { //IN
            queryWrapper.in(name, this.searchGroup[name])
          }
        }
      })
    }

    //拼接据视图默认天数配置条件
    if (isByStru == true) {
      // if (this.defaultQueryConfig && this.defaultQueryConfig.field && this.defaultQueryConfig.days) {
      //   let days = Number(this.defaultQueryConfig.days - 1)
      //   let startDate = this.dates.getDateBeforeDays(-days)
      //   let endDate = new Date().format(this.dates.defaultDateTimePattern)
      //   queryWrapper.between(this.defaultQueryConfig.field, [startDate, endDate])
      // }
      //
      // //数据视图所配置的默认字段查询条件
      // this.columns.filter(column => this.strings.isNotBlank(column.defaultQuery)).forEach(column2 => {
      //   queryWrapper.eq(column2.name, column2.defaultQuery)
      // })
    }

    //如果有排序，则至少需要一个查询条件，否则会报错
    if ((this.orderField || (paramsOld && paramsOld.orderString))
      && (
        (!queryWrapper._queryConditions || queryWrapper._queryConditions.length < 1)
        ||        (queryWrapper._queryConditions && queryWrapper._queryConditions.length == 1 && this.strings.isBlank(queryWrapper._queryConditions[0].val))
      )
    ) {
      //只有一个查询条件，并且查询值为空的时候
      if (queryWrapper._queryConditions && queryWrapper._queryConditions.length == 1 && this.strings.isBlank(queryWrapper._queryConditions[0].val)) {
        queryWrapper = this.$newWrapper()
      }
      queryWrapper.eq('1', 1)
    }

    queryConditions.push(...queryWrapper.queryConditions)

    // 拼接视图条件
    if (this.queryWrapper != null && this.queryWrapper instanceof this.queryWrappers.getWrapperClass()) {
      queryConditions.push(...this.queryWrapper.queryConditions)
    }

    // 拼接一次性视图条件
    if (this.queryWrapperOnce != null && this.queryWrapperOnce instanceof this.queryWrappers.getWrapperClass()) {
      queryConditions.push(...this.queryWrapperOnce.queryConditions)
      this.queryWrapperOnce = null
    }


    //拼接路由参数，如果有的话,只保留路由参数
    let params = this.$route.query
    let autoQuery = 'autoQuery'
    if (params[autoQuery] != null && params[autoQuery] == true) {
      Object.keys(params).forEach((key) => {
        if (Object.prototype.hasOwnProperty.call(params, key)) {
          if (this.primaryKey == key) {
            queryWrapper = this.$newWrapper()
            queryWrapper.eq(this.primaryKey, params[key])
            queryConditions = queryWrapper.queryConditions
          }
        }
      })
    }


    return queryConditions.length == 0 ? null : JSON.stringify(queryConditions)
  },
  // 生成排序条件
  generateOrder() {
    let orderConditions = []
    let wrapper = this.$newWrapper()
    if (this.cpDefaultSort.prop && (!this.userOrder || this.userOrder.length == 0)) {
      // 如果有默认排序 且 没有进行用户排序
      let {prop, order} = this.cpDefaultSort

      // 如果排序状态为后端排序，才进行条件拼接
      // let length = this.columns.filter((col) => col.name == prop && col.sortable == 'custom').length
      let length = this.columns.filter((col) => col.name == prop).length
      if (length > 0) {
        wrapper.orderBy(order, prop)
      }
    }
    this.userOrder.forEach((o) => {
      wrapper.orderBy(o.rule, o.field)
    })
    orderConditions = wrapper.orderConditions

    // 拼接自定义排序
    if (this.queryWrapper != null && this.queryWrapper instanceof this.queryWrappers.getWrapperClass()) {
      orderConditions.push(...this.queryWrapper.orderConditions)
    }
    return orderConditions.length == 0 ? null : JSON.stringify(orderConditions)
  },
  parseRules(rules) {
    const obj = {}
    Object.keys(rules).forEach((objKey) => {
      const tmp = []
      rules[objKey].forEach((item) => {
        try {
          if (item) {
            if (item.constructor !== String) {
              /**
               * @Description：兼容tdesign，转换下规则，不然会报错
               * @Author wyt
               * @Date 2023-09-27
               */
              if (this.propIsTdesign && this.propIsTdesign == true && item.pattern) {
                item.pattern = new RegExp(item.pattern)
              }
              tmp.push(item)
            } else {
              tmp.push(JSON.parse(item))
            }
          }

        } catch(e) {
          console.error('解析规则失败，原因如下')
          console.error(e)
        }
      })
      obj[objKey] = tmp
    })
    return obj
  },
  getFetchReqParams(isByStru) { //获取请求参数
    if (isByStru == true) {
      let viewState = this.utils.loadUserState(this, this.propViewKey)

      if (viewState) {
        let viewStateOb = this.strings.isString(viewState) ? JSON.parse(viewState) : viewState
        if (!viewStateOb.groupname) viewStateOb.groupname = ''
        if (!viewStateOb.groupvalue) viewStateOb.groupvalue = ''
        if (viewStateOb.searchGroup) this.searchGroup = JSON.parse(viewStateOb.searchGroup)
        this.flowNodeValue = viewStateOb.flowNodeValue

        //this.tablePage.currentPage = viewStateOb.currentPage
        //this.tablePage.pageSize = viewStateOb.pageSize

        // params.queryString = viewStateOb.queryString
        // params.orderString = viewStateOb.orderString
        // params.currentPage = viewStateOb.currentPage
        // params.rowsPerPage = viewStateOb.rowsPerPage
      }
    } else {
      //保存用户状态
      // this.utils.updateUserState(this.propViewKey, {
      //   flowFieldName: this.strings.defaultIfBlank(this.flow.fieldName, ''),
      //   flowNodeValue: this.strings.defaultIfBlank(this.flowNodeValue, ''),
      //   //queryString: params.queryString,
      //   //orderString: params.orderString,
      //   // currentPage: params.currentPage,
      //   //pageSize: this.tablePage.pageSize,
      //   //rowsPerPage: params.rowsPerPage,
      //   //flowNode: params.flowNode,
      //   //userParam: params.userParam,
      //   //importTableName: params.importTableName,
      //   //tableFormData: this.tableForm && this.tableForm.data ? this.tableForm.data : {},
      // }, this)
    }

    const params = {
      orderString: this.generateOrder(),
      currentPage: this.tablePage.currentPage,
      rowsPerPage: this.tablePage.pageSize,
      flowNode: this.flowNodeValue,
      userParam: this.userParam,
      importTableName: this.importTableName
    }
    params.queryString = this.generateQuery(isByStru, params)
    if (this.propUserParam) params.userParam = this.propUserParam
    let reqType = 'get'
    let reqParam = {params}
    //console.log('列表配置标识：' + this.viewKeyDb + '，列表配置名称:' + this.viewName + '，查询参数如下', params)
    //参数过多，服务器异常，此处改为post请求
    if (this.listEntry.indexOf('pageWithStock') != -1) {
      reqType = 'post'
      reqParam = params
    }
    return {reqType, reqParam}
  },
  //插入新行
  async insertEvent(row, focusIndex = 0) {
    if (this.rows.length == 0 || this.rows[0][this.primaryKey]) {
      let record = row || {}
      this.rows.splice(0, 0, record)
      this.$refs.tbMain.loadData(this.rows)
      this.$nextTick(() => {
        setTimeout(() => {
          this.$refs.tbMain.setActiveRow(record)
        }, 500)
        // this.$refs.tbMain.setActiveRow(record)

        //聚焦第一个输入网格，setActiveRow之后就已经聚焦第一个单元格了
        /*  try{
            setTimeout(() => {
              if(focusIndex != -1) {
                let inpFirst = $(this.$refs.tbMain.$el).find('.edit-down-input:eq('+focusIndex+')').children('input')
                if (inpFirst.length > 0) inpFirst.click()
              }
            },333)
          }catch (e) {
          }*/
      })
    }
  },
  activeRowMethod({column, row}) {
    let rowIndex = this.getGrid().getRowIndex(row)
    if (true == row._isSaveing) {
      this.utilMessage.warning(`第${rowIndex + 1}行数据保存中，请稍后再编辑`)
      return
    }
    if (this.propActiveRowMethod && !this.propActiveRowMethod(column, row)) {
      return false
    }

    if (!this.editable) {
      return false
    }
    if (this.propEditConfigMode && this.propEditConfigMode == 'cell') {
      return true
    } else {
      let rowButtons = this.cpFilteredButtons(this.rowButtons, row)
      if (rowButtons.find((item) => item.key === 'vrb-edit')) {
        return true
      }
    }
    return false
  },
  // 行编辑、查看功能
  rowEdit(row, readonly) {
    if (this.editable && !readonly) {
      this.$refs.tbMain.setActiveRow(row)
      //聚焦第一个输入网格
      // try{
      //   setTimeout(() => {
      //     let inpFirst = $(this.$refs.tbMain.$el).find('.edit-down-input:eq(0)').children('input')
      //     if (inpFirst.length > 0) inpFirst.click()
      //   },333)
      // }catch (e) {
      // }
      return
    }
    this.viewFormReadOnly = readonly
    this.refreshCurrentRow(row, true)
  },
  // 刷新当前行
  async refreshCurrentRow(row, triggerMove) {
    const params = {}
    if (!row[this.primaryKey]) {
      return
    }
    this.isRefreshCurrentRow = true
    params[this.primaryKey] = row[this.primaryKey]
    if (true != this.propDisabledLoadFormGetFirst) {
      this.utilVue.loadShow(true)
    } else {
      let idOld = this.viewFormData ? this.viewFormData[this.primaryKey] : '-1'
      let idNew = row[this.primaryKey]
      if (idOld != idNew) {
        this.utilVue.loadShow(true)
      }
    }
    let queryEntry = this.queryEntry
    if (queryEntry.indexOf(`{id}`) != -1) {
      queryEntry = this.strings.replaceAll(queryEntry, '{id}', row[this.primaryKey])
    }
    this.$ajax.get(queryEntry, {params}).then((response) => {
      if (response.code == 0) {
        let returnData = {}
        // 视图获取回来的不一样
        if (this.queryEntry === 'data-view/find') {
          returnData = response.data.view
        } else {
          returnData = response.data
        }
        this.currentRow = this.rows.filter(row0 => row0[this.primaryKey] == row[this.primaryKey])[0]
        this.viewFormData = returnData
        this.utilVue.loadHide()
        this.$set(this, 'viewFormStatus', 'edit')
        this.viewFormVisible = true
        this.$nextTick(() => {
          const {afterMove, dataRefresh} = this.viewFormEvents
          if (afterMove && triggerMove) {
            afterMove(returnData, this.propInitData, this.viewFormStatus, triggerMove)
            // afterMove(row, this.propInitData)
          }
          if (dataRefresh && !triggerMove) {
            dataRefresh(returnData)
          }
          if (!dataRefresh && !triggerMove) {
            this.$refs.viewForm.form = global.utils.jsonClone(returnData)
          }
        })
        setTimeout(() => {
          this.isRefreshCurrentRow = false
        }, 1000)
      }
    }).catch(e => {
      console.error('refreshCurrentRow.error')
      console.error(e)
      // 异常后禁用表单
      this.viewFormReadOnly = true
      this.ocHideFormButtons()
    })
  },
  // 新增功能
  addnew() {
    if (this.editable) {
      this.activeFirst(true)
      return
    }
    if (this.propInitData && this.propParentPage && !this.propInitData[this.primaryKey]) {
      this.propParentPage.$emit('save')
    }

    this.viewFormReadOnly = false
    this.$set(this, 'viewFormStatus', 'addnew')
    this.currentRow = {}
    this.viewFormData = {}
    this.viewFormVisible = true
    this.$nextTick(() => {
      const {afterMove} = this.viewFormEvents
      if (afterMove) {
        afterMove({}, this.propInitData, this.viewFormStatus, this.viewFormStatus, true)
      }
    })
  },
  //获取上一行的数据
  viewPreviousRow() {
    let prevRowIndex = this.rows.indexOf(this.currentRow) - 1
    if (prevRowIndex < -1) { //用于解决dataview找不到下标的问题
      let selRow = this.rows.filter(row => row[this.primaryKey] == this.currentRow[this.primaryKey])[0]
      prevRowIndex = this.rows.indexOf(selRow) - 1
      if (prevRowIndex < -1) {
        return
      }
    }
    if (prevRowIndex < 0) { //获取上一页的数据
      this.tablePage.currentPage = this.tablePage.currentPage - 1
      this.autoOpenLast = true
      this.fetchData()
      return
    }
    this.currentRow = this.rows[prevRowIndex]
    this.setCurrent(this.currentRow)
    this.refreshCurrentRow(this.currentRow, true)
  },
  //获取下一行的数据
  viewNextRow() {
    let nextRowIndex = this.rows.indexOf(this.currentRow) + 1
    if (nextRowIndex < 1) { //用于解决dataview找不到下标的问题
      let selRow = this.rows.filter(row => row[this.primaryKey] == this.currentRow[this.primaryKey])[0]
      nextRowIndex = this.rows.indexOf(selRow) + 1
    }
    if (nextRowIndex > this.rows.length - 1) { //获取下一页的数据
      this.tablePage.currentPage = this.tablePage.currentPage + 1
      this.autoOpenFirst = true
      this.fetchData()
      return
    }
    this.currentRow = this.rows[nextRowIndex]
    this.setCurrent(this.currentRow)
    this.refreshCurrentRow(this.currentRow, true)
  },
  getRowByPK(pk) {
    return this.rows0.find((item) => item[this.primaryKey] == pk)
  },
  getColumnType(dicts, column, type) {
    if (this.isFlowField(column.property) && type == 'flowId') { //如果是流程，返回流程Id
      return this.flowNodes[0].flowId || ''
    }
    let currentColumn = this.cpColumns.filter(c => c.name == column.property)[0]
    return currentColumn[type] || ''
  },
  async exportMethod({options}) {
    let dicts = this.getFlowDict()
    const exportParam = {
      filename: options.filename,
      sheetName: options.sheetName,
      isHeader: options.isHeader,
      mode: options.mode,
      fields: JSON.stringify(options.columns.filter(column => column.property).map(column => {
        return {
          field: column.property,
          title: column.title,
          dict: this.getColumnType(dicts, column, 'dict'),
          datePattern: this.getColumnType(dicts, column, 'datePattern'),
          flowId: this.getColumnType(dicts, column, 'flowId')
        }
      }))
    }
    if (this.strings.isBlank(exportParam.filename) || exportParam.filename == '导出_{0}') {
      exportParam.filename = this.$route.meta.title
    }
    const {reqParam} = this.getFetchReqParams()
    let params = reqParam.params || {}
    Object.assign(params, exportParam)
    if (options.mode == 'all') { //全部数据
      params.currentPage = 1
      params.rowsPerPage = -1
    } else {
      params.currentPage = this.tablePage.currentPage
      params.rowsPerPage = this.tablePage.pageSize
    }
    params.listEntry = this.listEntry
    params.isAll = options.mode == 'all'
    let exportEntry = this.listEntry //替换成export
    exportEntry = exportEntry.substr(0, exportEntry.lastIndexOf('/'))
    if (this.strings.isEmpty(exportEntry)) {
      return
    } else {
      exportEntry = exportEntry.concat('/exportFullData')
    }
    if (this.strings.isNotBlank(this.formConfig.exportAddr)) {
      exportEntry = this.formConfig.exportAddr
    }

    this.utilVue.loadShow(true)
    this.$ajax.get(exportEntry, {params}).then(resp => {
      if (resp.code == 0) {
        this.utilMessage.success('导出成功，开始下载')
        global.utils.downloadrRes(resp.data)
        setTimeout(() => {
          this.utilVue.loadHide()
        }, 2000)
      }
    })
  },
  setIsDataviewLoadStru() {
    setTimeout(() => {
      this.isDataviewLoadStru = false
      //嵌套在下拉框里面会有问题
      // $(this.$refs.tbMain.$el).find('.vxe-grid--form-wrapper,.vxe-grid--toolbar-wrapper').hide()
      //表单区域可滚动高度大于55px,则显示切换搜索区域 按钮
      // if (this.$refs && this.$refs.tbMain && $(this.$refs.tbMain.$el).find('.vxe-grid--form-wrapper').length > 0 ) {
      //   if ( $(this.$refs.tbMain.$el).find('.vxe-grid--form-wrapper')[0].scrollHeight > 55) {
      //     $(this.$refs.tbMain.$el).find('.vxe-button--content:contains("展开查询"):last').parent().show()
      //   } else {
      //     $(this.$refs.tbMain.$el).find('.vxe-button--content:contains("展开查询"):last').parent().hide()
      //   }
      // }
      // setTimeout(() => {
      //   $(this.$refs.tbMain.$el).removeClass('dataview-load-stru')
      //   // $(this.$refs.tbMain.$el).find('.vxe-grid--form-wrapper,.vxe-grid--toolbar-wrapper').fadeIn('fast')
      // }, 100)

      // $(this.$refs.tbMain.$el).find('.vxe-grid--form-wrapper,.vxe-grid--toolbar-wrapper').fadeIn('fast')
    }, 1000)
  },
  // 获取数据字典
  async fetchDict() {
    let dicts = {}
    // 流程字典
    dicts = this.getFlowDict()

    this.baseColumns
      .filter((col) => this.strings.isNotBlank(col.dict))
      .forEach((col) => {
        dicts[col.name] = this.utils.getDictDataList(col.dict)
        // 将数据字典加入到 viewFormDictionaries 中，以实现表单界面中统一格式访问
      })
    if (Object.keys(this.viewFormDictionaryDef).length === 0) {
      this.viewFormDictionaries = dicts
      this.makeUserQuery()
      this.setIsDataviewLoadStru()
      return
    }

    // api URL  同一个URL 不进行多次请求
    let apis = []
    let urlSet = new Set()
    let dictDef = this.viewFormDictionaryDef

    //排除掉树，树在编辑界面加载
    let elTrees = this.baseColumns.filter(item => item.dict == 'el_tree')
    let treeSourceArr = []
    if (elTrees != null && elTrees.length > 0) elTrees.forEach(item => treeSourceArr.push(item.source))

    Object.keys(dictDef)
      .filter((key) => !treeSourceArr.includes(dictDef[key]) && this.strings.isNotBlank(key) && !dictDef[key].toLowerCase().trim().startsWith('select'))
      .forEach((key) => {
        urlSet.add(this.viewFormDictionaryDef[key])
      })
    for (const url of urlSet) {
      apis.push(
        new Promise((resolve, reject) => {
          this.$ajax
            .get(url, {params: {onlyBusFields: true}})
            .then((resp) => {
              let obj = {url, data: resp.data}
              resolve(obj)
            })
            .catch((e) => resolve(e))
        })
      )
    }

    try {
      let res = await Promise.all(apis)
      res.forEach((item) => {
        let {url, data} = item
        Object.keys(dictDef)
          .filter((key) => dictDef[key] === url)
          .forEach((key) => (dicts[key] = data))
      })
    } catch (e) {
      this.utilMessage.error(e.msg)
    }

    let sqlDef = {}
    Object.keys(dictDef)
      .filter((key) => this.strings.isNotBlank(key) && dictDef[key].toLowerCase().trim().startsWith('select'))
      .forEach((key) => {
        sqlDef[key] = this.viewFormDictionaryDef[key]
      })
    if (Object.keys(sqlDef).length == 0) {
      this.viewFormDictionaries = dicts
      this.makeUserQuery()
      this.setIsDataviewLoadStru()
      return
    }
    const params = {contents: JSON.stringify(sqlDef)}
    // await this.$ajax.get('/program/dict/list', {params}).then((response) => {
    //   if (response.code == 0) {
    //     this.viewFormDictionaries = {...dicts, ...response.data}
    //   } else {
    //     this.utilMessage.error(response.msg)
    //     this.viewFormDictionaries = dicts
    //   }
    //
    // })
    this.makeUserQuery()
    this.setIsDataviewLoadStru()
  },
  // 获取流程字典
  getFlowDict() {
    let dicts = {}
    // 流程字典
    let flowField = this.strings.camelCase(this.flow.fieldName)
    if (this.strings.isNotBlank(flowField)) {
      dicts[flowField] = this.flowNodes.map((node) => {
        return {value: node.value, label: node.name, color: node.color}
      })
    }
    return dicts
  },
  getColumnValue(column, row, onlyText) { //获取列的值
    let oldValue = row[column.name]
    if (column.queryType == 'FortenDataviewDown') {
      return oldValue
    }
    //原样显示
    if (column.showNoDict) {
      return oldValue
    }
    if (this.isFlowField(column.name) || !this.strings.isBlank(column.dict)) {
      oldValue = this.getDictLabel(column.name, column.dict, row[column.name], onlyText)
    } else if (this.viewFormDictionaries[column.name] && this.strings.isBlank(column.dict)) {
      oldValue = this.getFormDictLable(column.name, this.viewFormDictionaries[column.name], row[column.name])
    }
    if (this.strings.isNotBlank(column.sourceVuex) && this.utilVuex[column.sourceVuex]) {
      let indexIndex = this.utilVuex[column.sourceVuex]().findIndex(find => find.value == oldValue)
      if (indexIndex != -1) {
        oldValue = this.utilVuex[column.sourceVuex]()[indexIndex].label
      }
    }

    //sourceVuex
    let columnValue = this.utilFieldMap.value(column.name, oldValue, 'dataview', this.propViewKey, row)

    return column.linkRoute && row[column.linkRoutePrimaryKey] ? `<a class="is-underline" style="color:orange" title="点击跳转" onclick="global.utils.openMenu('${column.linkRoute}', { id: '${row[column.linkRoutePrimaryKey]}' })"><span class="el-link--inner">${columnValue}</span></a>` : columnValue
  },
  getDictLabel(fieldName, dictType, value, onlyText) {
    // 字段名 、字典类型、值
    // 判断是否是流程字段
    if (this.isFlowField(fieldName)) {
      let dicts = this.getFlowDict()
      if (!dicts[fieldName]) {
        return ''
      }
      let result = dicts[fieldName].filter((dict) => dict.value == value)[0]
      if (onlyText) return result.label
      return result ? `<span style="background:${result.color};padding: 3px;border-radius: 5px;color:#fff">${result.label}</span>` : ''
    }
    return this.utils.getDictLabel(value, dictType, '', !onlyText)
  },
  getFormDictLable(fieldName, formDict, value) {
    if (!formDict) {
      return ''
    }
    let result = formDict.filter((dict) => dict.id == value)[0]
    return result ? result.name : value
  },
  isFlowField(fieldName) {
    return fieldName === this.strings.camelCase(this.flow.fieldName)
  },
  // 根据视图设置，将按钮添加到集合中
  addDefaultButtons() {
    const config = this.configReserveButtons
    if (config.showViewButtonDelete) {
      this.viewButtons.unshift({
        key: 'vb-delete',
        title: '删除',
        type: 'danger',
        icon: 'el-icon-delete',
        iconStatic: 'delete'
      })
    }
    if (config.showViewButtonAdd) {
      this.viewButtons.unshift({key: 'vb-add', title: '添加', type: 'success', icon: 'el-icon-plus',
        iconStatic: 'add'})
    }
    if (config.showViewButtonRefresh) {
      this.viewButtons.unshift({
        key: 'vb-refresh',
        title: '刷新',
        type: '',
        icon: 'el-icon-refresh',
        iconStatic: 'refresh'
      })
    }
    if (config.showRowButtonDelete) {
      this.rowButtons.unshift({
        key: 'vrb-delete',
        title: '',
        type: 'danger',
        icon: 'el-icon-delete',
        iconStatic: 'delete'
      })
    }
    if (config.showRowButtonEdit) {
      this.rowButtons.unshift({key: 'vrb-edit', title: '', type: 'primary', icon: 'el-icon-edit',
        iconStatic: 'edit'})
    }
    if (config.showRowButtonDetail) {
      this.rowButtons.unshift({key: 'vrb-view', title: '', type: 'primary', icon: 'el-icon-search',
        iconStatic: 'view'})
    }
    if (config.showRowButtonSave) {
      this.rowButtons.unshift({
        key: 'vrb-save',
        title: '保存',
        type: 'success',
        icon: 'el-icon-check',
        iconStatic: 'save'
      })
    }
    /*if (this.flow) {
      this.rowButtons.unshift({key: 'vrb-flow-log', title: '', type: 'primary', icon: 'el-icon-lollipop'})
    }*/
    if (config.showViewFormButtonDelete) {
      this.viewFormButtons.unshift({
        key: 'vfb-delete',
        title: '删除',
        type: 'danger',
        icon: 'el-icon-delete',
        iconStatic: 'delete'
      })
    }
    if (config.showViewFormButtonSave) {
      this.viewFormButtons.unshift({
        key: 'vfb-cancel',
        title: '取消',
        type: 'default',
        icon: 'el-icon-arrow-left',
        iconStatic: 'cancel'
      })
      this.viewFormButtons.unshift({
        key: 'vfb-save',
        title: '保存',
        type: 'primary',
        iconStatic: 'save',
        // icon: 'el-icon-disk'
      })
    }
    if (config.showViewFormButtonAdd) {
      this.viewFormButtons.unshift({
        key: 'vfb-add',
        title: '添加',
        type: 'success',
        icon: 'el-icon-plus',
        iconStatic: 'add'
      })
    }
  },
  // 设置新增和编辑状态下的界面按钮状态,hidden 和 sysHidden中有一个属性为true，按钮就不显示
  setVFBSystemHidden() {
    let btn = null
    if (this.viewFormStatus === 'addnew') {
      btn = this.viewFormButtons.find((item) => item.key === 'vfb-save')
      btn && this.$set(btn, 'systemHidden', false)

      btn = this.viewFormButtons.find((item) => item.key === 'vfb-cancel')
      btn && this.$set(btn, 'systemHidden', false)

      btn = this.viewFormButtons.find((item) => item.key === 'vfb-add')
      btn && this.$set(btn, 'systemHidden', true)

      btn = this.viewFormButtons.find((item) => item.key === 'vfb-delete')
      btn && this.$set(btn, 'systemHidden', true)
    } else {
      btn = this.viewFormButtons.find((item) => item.key === 'vfb-save')
      btn && this.$set(btn, 'systemHidden', false)

      btn = this.viewFormButtons.find((item) => item.key === 'vfb-cancel')
      btn && this.$set(btn, 'systemHidden', true)

      btn = this.viewFormButtons.find((item) => item.key === 'vfb-add')
      btn && this.$set(btn, 'systemHidden', false)

      btn = this.viewFormButtons.find((item) => item.key === 'vfb-delete')
      btn && this.$set(btn, 'systemHidden', false)
    }
  },
  // 处理添加的自定义列
  customColums() {
    const cols = this.propCustomCols || []
    cols.forEach((col) => {
      if (col.cmode === 'extra') {
        //
        const index = this.columns.findIndex((oriCol) => oriCol.name === col.after)
        if (index > -1) {
          this.columns.splice(index + 1, 0, col)
        } else {
          this.columns.push(col)
        }
      } else if (col.cmode === 'before') {  //开头
        const index = this.columns.findIndex((oriCol) => oriCol.name === col.after)
        if (index > -1) {
          this.columns.splice(index + 1, 0, col)
        } else {
          this.columns.unshift(col)
        }
      } else {
        const index = this.columns.findIndex((oriCol) => oriCol.name === col.name)
        if (index > -1) {
          this.columns[index].cmode = 'edit'
        }
      }
    })
  },
  isShowButton(button, data, isCpRowButton = false) {
    let {key, showCondition} = button
    let title2 = button.title
    if (this.propOnlyQueryAll != undefined && this.propOnlyQueryAll == true && key != 'vrb-view') {
      return false
    }
    //不显示编辑按钮
    if (this.flow && this.flowNodes.length > 0) {
      // 行按钮，依据流程先进行过滤
      let {flow, strings, flowNodes, viewFormData} = this
      let flowField = strings.camelCase(flow.fieldName)
      let flowNodeValue = data[flowField]
      let flagShow = 'flagShow-'

      if (!flowNodeValue && this.propInitData) {
        // 从初始数据中获取流程状态字段
        flowNodeValue = this.propInitData[flowField]
      }
      let node = flowNodes.find((node) => node.value == flowNodeValue)

      if (node) {
        let flagKey = strings.hyphencamelCase(flagShow + key)
        if (node[flagKey] != null && node[flagKey] == false) {
          return false
        }
      }
    }

    //按钮流程过滤，只有子视图才有用

    if (this.btnNodeMap && this.propCheckFlowParam) {
      let checkFlowBusFlowStatus = this.propCheckFlowParam.checkFlowBusFlowStatus
      let buttonKey = button.key
      switch (buttonKey) {
      case 'vb-add': //添加
        if (this.btnNodeMap.showViewButtonAdd && this.btnNodeMap.showViewButtonAdd.length > 0 && !this.btnNodeMap.showViewButtonAdd.includes(checkFlowBusFlowStatus)) return false
        break

      case 'vb-delete': //删除
        if (this.btnNodeMap.showViewButtonDelete && this.btnNodeMap.showViewButtonDelete.length > 0 && !this.btnNodeMap.showViewButtonDelete.includes(checkFlowBusFlowStatus)) return false
        break
      default: //自定义按钮
        if (this.btnNodeMap[key] && this.btnNodeMap[key].length > 0 && !this.btnNodeMap[key].includes(checkFlowBusFlowStatus)) return false
      }
    }

    //工具栏打印按钮不做控制
    if (button.flagPrint && button.btntype && button.btntype == 'view') {
      return true
    }
    if (!isCpRowButton) {
      return this.isShowCondition(button, data)
    }

    return true
  },
  isShowCondition(button, data, isRowBtn = false) {
    let { showCondition} = button

    // 根据行启用编辑条件进行判断
    if (isRowBtn && this.formConfig.rowEnableCondition && ['vrb-delete','vrb-edit'].includes(button.key)) {
      let result = true
      try {
        result = eval(this.formConfig.rowEnableCondition)
      } catch (e) {
        console.error('行启用编辑条件格式化失败',this.formConfig.rowEnableCondition)
        console.error(e)
        return false
      }
      if (!result) {
        return false
      }
    }
    if (this.strings.isBlank(showCondition)) {
      return true
    }

    try {
      let propReadonly = this.cpFormReadonly
      return eval(showCondition)
    } catch (e) {
      console.error('按钮条件格式化失败',showCondition)
      console.error(e)
      return false
    }
  },
  isSelectable(row, index) {
    return true
    // return this.isShowButton({key: 'vrb-delete'}, row)
  },
  handlePageSearch(param) {
    if (param && param.data && param.data.pageSearch) {
      this.pageSearch = this.strings.trimrl(param.data.pageSearch)
    }
    this.listLoading = true
    this.rows = this.rows0.filter((item) => {
      let find = false
      Object.keys(item).map((col) => {
        if (item[col] && item[col].toString().indexOf(this.pageSearch) > -1) {
          find = true
          return true
        }
      })
      return find
    })
    this.$refs.tbMain.loadData(this.rows).then(() => {
      this.listLoading = false
    })
  },

  async rowSaveRefresh() {
    let that = this
    let rowData = this.$refs.tbMain.$refs.xTable.getActiveRecord()
    let row = rowData.row
    const errMap = await this.$refs.tbMain.validate(row).catch(errMap => errMap)
    if (!errMap) {
      await this.$ajax.post(this.saveEntry, row).then(response => {
        if (response.success) {
          if (!row[this.primaryKey]) { //新增数据刷新
            let newRecord = this.rows.find(item => item[this.rowPK] == row[this.rowPK])
            this.$set(newRecord, this.primaryKey, response.data[this.primaryKey])
          }
        }
        if (response.success) {
          this.$refs.tbMain.clearActived()
          that.propParentPage && that.propParentPage.$emit('refresh-row') && that.propParentPage.$emit('refresh-grid')
          let nextRowIndex = rowData.rowIndex + 1
          let rowNext = that.rows[nextRowIndex]
          this.$nextTick(() => {
            setTimeout(() => {
              this.columns.forEach((column) => {
                if (column.name == 'packageQty') {
                  this.$refs.tbMain.setActiveCell(rowNext, column.name)
                }
              })
            }, 1000)
          })
        }
      })
    }
  },
  rowStyle({row}) {
    let rowBgColor = 'rowBgColor'
    if (row[rowBgColor]) {
      return {
        color: row[rowBgColor]
      }
    }
  },

  /**手动清除单元格激活状态
   */
  clearActived() {
    this.$refs.tbMain.clearActived()
  },

  /**获取编辑列在列表中显示的索引
   * @param columnName 列名称，区分大小写
   * @return columns 为空，columnName，或者未找到对应列，返回-1
   * @example this.$refs.childDataView.getColumnEditIndex('packageUnit')
   */
  getColumnEditIndex(columnName) {
    if (!this.columns || !columnName) {
      return -1
    }
    let showNum = -1
    let findIndex = -1
    this.columns.filter((item) => !item.hidden).some((item) => {
      // eslint-disable-next-line no-plusplus
      showNum++
      if (item.name == columnName) {
        findIndex = showNum
        return true
      }
      return false
    })
    return findIndex
  },

  /**500毫秒后聚焦到某一个编辑单元格，因为同时活动行只会存在一行，所以此处直接查找对应索引的元素即可
   * @param columnName 列名称，区分大小写
   * @example this.$refs.childDataView.focusEditCell('packageUnit')
   */
  async focusEditCell(columnName) {
    setTimeout(() => {
      let findIndex = this.getColumnEditIndex(columnName)
      if (findIndex == -1) return

      let inpEdit = $(this.$refs.tbMain.$el).find('.vxe-table--main-wrapper').find('.col--actived:eq(' + findIndex + ')').find('input:first')
      // inpEdit.focus()
    }, 500)
  },
  expandVisibleMethod({row}) { //是否显示展开按钮
    return row.showExpand
  },
  loadContentMethod({row}) {
    return new Promise(resolve => {
      this.$emit('expandMethod', row, callback => {
        resolve()
      })
    })
  },
  setUserParam(userParam) {
    this.userParam = userParam
  },

  //设置表格的尺寸，medium【默认】, small, mini
  setTbMainSize(tbMainSize) {
    this.tbMainSize = tbMainSize
  },
  //隐藏列
  hideColumn(fieldName) {
    this.$refs.tbMain.hideColumn(this.$refs.tbMain.getColumnByField(fieldName))
  },
  //显示列
  showColumn(fieldName) {
    this.$refs.tbMain.showColumn(this.$refs.tbMain.getColumnByField(fieldName))
  },

  //分组条件选中
  searchGroupSelect(item1, item2) {
    this.listLoading = true
    this.searchGroupDisabled = true
    if (!this.searchGroup[item1.name]) {
      this.searchGroup[item1.name] = []
    }
    if (!this.searchGroup[item1.name].includes(item2.value)) {
      this.searchGroup[item1.name].push(item2.value)
    }
    item2.checked = true

    this.fetchData()
  },
  //清除分组条件
  searchGroupClear(item, item2) {
    this.listLoading = true
    this.searchGroupDisabled = true
    item2.checked = false
    if (this.searchGroup[item.name]) {
      let findIndex = this.searchGroup[item.name].findIndex(v => v == item2.value)
      if (findIndex != -1) this.searchGroup[item.name].splice(findIndex, 1)
    }

    this.fetchData()
  },
  isActiveSearchGroup(name, value) {
    return this.searchGroup[name] && this.searchGroup[name].includes(value)
  },
  //获取table样式，如果没有分组条件则宽度占满，否则左边预留分组条件
  getStyle() {
    if (!this.searchGroupFields || this.searchGroupFields.length < 1) return {}
    // return {marginLeft: '120px', width: 'auto', paddingLeft: '9px'}
    return {}
  },

  searchGroupFun(name, item) {
    let input = this.strings.trimrl($('#input' + name).val())
    let index = this.searchGroupData.findIndex(ob => ob.name == name)
    if (index == -1) return
    if (this.strings.isBlank(input)) {
      this.searchGroupData[index].list = this.searchGroupData[index].listold
      return
    }
    this.searchGroupData[index].list = this.searchGroupData[index].listold.filter(ob => ob.label.indexOf(input) > -1
      || this.pyutils.getAllFirstLetter(ob.label).toLowerCase().indexOf(input.toLowerCase()) > -1
      || this.pyutils.chineseToPinYin(ob.label).toLowerCase().indexOf(input.toLowerCase()) > -1)
    this.$set(this.searchGroupData)
  },

  getSearchGroupList(item, forceUpdate) {
    if (item.dict) return item.list
    let input = this.strings.trimrl($('#input' + item.name).val())
    let index = this.searchGroupData.findIndex(ob => ob.name == item.name)

    if (index == -1) return []

    if (this.strings.isBlank(input)) {
      this.searchGroupData[index].list = this.searchGroupData[index].listold
    } else {
      this.searchGroupData[index].list = this.searchGroupData[index].listold.filter(ob => ob.label.indexOf(input) > -1
        || this.pyutils.getAllFirstLetter(ob.label).toLowerCase().indexOf(input.toLowerCase()) > -1
        || this.pyutils.chineseToPinYin(ob.label).toLowerCase().indexOf(input.toLowerCase()) > -1)
    }

    //如果包含选中元素，则将已选中的元素置顶
    // this.searchGroup[name] && this.searchGroup[name].includes(value)

    if (this.searchGroup[item.name] && this.searchGroup[item.name].length > 0) {
      this.searchGroup[item.name].forEach(value => {
        let findIndex2 = this.searchGroupData[index].list.findIndex(data => data.val == value)
        if (findIndex2 != -1) {
          let dataRemove = this.searchGroupData[index].list[findIndex2]
          this.searchGroupData[index].list.splice(findIndex2, 1)
          this.searchGroupData[index].list.unshift(dataRemove)
        }
      })
    }
    if (forceUpdate && forceUpdate == true) {
      this.$forceUpdate()
    }
    return this.searchGroupData[index].list
  },

  showTooltipMethod({type, column, row, items, _columnIndex}) {
    if (!column.params || column.params.expandColumn || column.params.linkRoute) {
      return null
    }
    if (column.params.datePattern) {
      return column.title + ':' + this.dates.toDate(row[column.property], column.params.datePattern)
    }
    return this.getColumnValue(column.params, row, true)
  },


  //加载分组数据源
  loadGroupUrl() {
    if (this.searchGroupData) {
      setTimeout(() => {
        Object.keys(this.searchGroupData).forEach(key => {
          if (this.strings.isNotBlank(this.searchGroupData[key].groupUrl)) {
            this.searchGroupData[key].list = []
            this.searchGroupData[key].listold = []
            const params = {
              orderString: this.generateOrder(),
            }
            params.queryString = this.generateQuery(false, params)
            this.$ajax.get(this.searchGroupData[key].groupUrl, {params}).then(resp => {
              console.log('searchGroupData.resp.data.' + key, resp.data)
              if (resp.success && resp.data) {
                this.searchGroupData[key].list = resp.data
                this.searchGroupData[key].listold = resp.data

                // //设置选中
                let name = this.searchGroupData[key].name
                if (this.searchGroup[name] && this.searchGroup[name].length > 0) {
                  this.searchGroupData[key].list.filter(ob => this.searchGroup[name].includes(ob.value)).forEach(ob2 => ob2.checked = true)
                  let isRemove = false

                  //分组值在数据源中不存在时，清除分组条件，重新查询
                  for (let i = 0; i < this.searchGroup[name].length; i += 1) {
                    let findIndex = this.searchGroupData[key].list.findIndex(ob => ob.value == this.searchGroup[name][i])
                    if (findIndex == -1) {
                      isRemove = true
                      this.searchGroup[name].splice(i, 1)
                    }
                  }
                  if (isRemove) this.fetchData()
                }
              } else {
                //清楚选中
                if (this.searchGroup[key]) this.searchGroup[key] = []
              }
              this.$forceUpdate()
            })
          }
        })
      }, 500)
    }
  },
  // 顶部合计
  sumTop() {
    if (!this.listEntry || !this.formConfig || !this.formConfig.flagSumTop || !this.columns) {
      return
    }
    if (this.sumTopColumns.length < 1) {
      this.columns.forEach((item) => {
        let property = item.name.toLowerCase()
        if (
          (property.indexOf('amount') != -1 && property.indexOf('sum') != -1)

          || (property.indexOf('qty') != -1 && property.indexOf('sum') != -1)
        ) return true
        if (property.indexOf('amount') != -1 || property.indexOf('qty') != -1) {
          this.sumTopColumnsName.push(item.name)
          // []
          this.sumTopColumns.push({
            name: item.name,
            title: item.title + '：',
            value: 0
          })
        }
      })
    } else {
      this.sumTopColumns.forEach(ob => {
        ob.value = 0
      })
    }

    if (this.sumTopColumnsName.length < 1) return
    let getUrl = this.listEntry.substring(0, this.listEntry.lastIndexOf('/')) + '/sumTop'
    let sumTopUrl = this.formConfig.sumTopUrl
    if (this.strings.isNotBlank(sumTopUrl)) {
      getUrl = sumTopUrl
    }
    const params = {
      orderString: this.generateOrder(),
      sumFields: this.sumTopColumnsName.join(',')
    }
    params.queryString = this.generateQuery(false, params)
    this.$ajax.get(getUrl, {params}).then((response) => {
      if (response.code == 0 && response.data) {
        this.sumTopColumns.forEach(ob => {
          if (response.data[ob.name]) {
            ob.value = this.utilNum.toFixed(response.data[ob.name])
          } else {
            ob.value = 0
          }
        })
      }
    })
  },

  //动态行样式
  rowClassName({row, rowIndex}) {
    if (this.rowAlertFun) {
      try {
        if (this.rowAlertFun(row)) return 'row-alert'
      } catch (e) {
        console.log('rowClassName.e', e)
      }
    }
  },

  //鼠标移动
  mousemove() {
    this.autoFetchCycleOp('2', null)
  },
  //添加或者移除定时刷新定时器
  autoFetchCycleOp(opType, msg) {
    if (!this.formConfig.autoFetchCycle) {
      return
    }
    let autoFetchCycle = parseInt(this.formConfig.autoFetchCycle, 0)
    if (autoFetchCycle <= 0) {
      return
    }
    // eslint-disable-next-line default-case
    switch (opType) {
    case '1':  //先移除再添加
      try {
        clearInterval(this.autoFetchCycleTimer)
        // eslint-disable-next-line no-empty
      } catch (e) {
      }
      if (msg) {
        this.utilMessage.info(msg + '，周期' + autoFetchCycle + '秒')
      }
      this.autoFetchCycleTimer = setInterval(this.autoFetchCycleExec, autoFetchCycle * 1000)
      break
    case '2':  //移除
      try {
        clearInterval(this.autoFetchCycleTimer)
        // eslint-disable-next-line no-empty
      } catch (e) {
      }
      if (msg) this.utilMessage.info(msg)
      break
    }
  },
  //添加或者移除定时刷新定时器
  autoFetchCycleExec() {
    this.utilMessage.info('开始自动刷新数据')
    this.fetchData()
  },

  //切换左侧分组显示方式
  toggleLeftGroup() {
    this.isCollapse = !this.isCollapse
  },

  //切换左侧分组显示方式
  toggleLeftGroupShowHide() {
    this.isHide = !this.isHide
  },

  //鼠标事件 grid
  keydownMonitor({$event}) {
    let { code, target } = $event
    if (code == 'F4') {
      this.activeFirst()
    }
  },

  //鼠标事件 盒子
  async keydownMonitorBox(param) {
    let event = param.$grid ? param.$event : param
    let { code, target } = event
    // eslint-disable-next-line default-case
    switch (code) {
    case  'Enter': //回车
    {
      //不自动激活
      if (this.cpDisabledActiveNext) {
        return
      }
      let activeRow = this.getGrid().getCurrentRecord()
      if (!this.propOnlyQuery) { //嵌套在下拉表格中
        this.activeNext()
      }
      break
    }
    case  'F2': //f2 确认
      //
      await this.getGrid().toggleCheckboxRow(this.currentRow)
      this.handleCheckboxChange(
        {
          row: this.currentRow,
          checked: this.getGrid().isCheckedByCheckboxRow(this.currentRow)
        }
      )
      break
    case  'F3': //f2 确认
      if (this.propOnlyQuery) {
        if (this.showCheckbox) { //多选
          // this.handleCheckboxChange({row: this.currentRow, checked: this.getGrid().isCheckedByCheckboxRow(this.currentRow) })
          this.$emit('extra-button-click', {
            data: [this.currentRow],
            rows: this.rows0,
            button: {
              key: 'confirm'
            },
          })
        } else { //单选
          this.handleCurrentRowChange({
            row: this.currentRow,
            oldRow: this.currentRow,
          })
        }
      }
      break
    case  'ArrowDown': //方向键下
    {
      let nextRowIndex = this.rows.indexOf(this.currentRow) + 1
      this.currentRow = this.rows[nextRowIndex]
      if (!this.currentRow) {
        this.currentRow = this.rows[0]
      }
      this.setCurrent(this.currentRow)
      break
    }
    case  'ArrowUp': //方向键上
    {
      let nextRowIndex = this.rows.indexOf(this.currentRow) - 1
      this.currentRow = this.rows[nextRowIndex]
      if (!this.currentRow) {
        this.currentRow = this.rows[this.rows.length - 1]
      }
      this.setCurrent(this.currentRow)
      break
    }
    }
  },
  // 验证
  _validateOnly(callSuccess) {
    this.isRefreshCurrentRow = true
    const {beforeSave, validate} = this.viewFormEvents
    if (validate) {
      let validateResult = false
      if (this.propIsTdesign && this.propIsTdesign == true) { //兼容tdesign
        validate().then( result => {
          if (result && result == true) {
            if (beforeSave && !beforeSave()) {
              this.isRefreshCurrentRow = false
              return false
            }

            if (callSuccess) {
              callSuccess()
            }
          }
        })
      } else {
        this.validatePromise(validate).then( result => {
          if (result) {
            if (beforeSave && !beforeSave()) {
              this.isRefreshCurrentRow = false
              return false
            }
            if (callSuccess) {
              callSuccess()
            }
          }
        })
      }
    }
  },
  // 编辑界面保存动作，流程提交动作
  _viewFormSaveOnly() {
    this.isRefreshCurrentRow = true
    this.flagSuccessSave = false
    let params = {}
    // 视图保存采用纯文本传输的方式，此处就是兼容这个操作
    if (this.propIsPostString) {
      params = {contents: JSON.stringify(this.viewFormData)}
    } else {
      params = this.viewFormData
      //追加拦截器需要使用的参数
      params = this.utils.appendParamForInterceptor(this, 'dataviewsave', params)
      if (!this.utilDataview.beforeSave(this, params)) return
    }
    this.formAutoSaveing()
    this.utilVue.loadShow(true, null, '自动保存中,请稍候')
    this.$ajax.post(this.saveEntry, params).then(response => {
      this.utilVue.loadHide()
      this.flagSuccessSave = response.success
      if (!this.flagSuccessSave) {
        this.formAutoSaveError()
        return
      }
      this.utilMessage.success(response.msg)
      if (!this.viewFormData[this.primaryKey]) {
        this.$set(this.viewFormData, this.primaryKey, response.data[this.primaryKey])
      }
      Object.keys(response.data).forEach(key => {
        this.$set(this.viewFormData, key, response.data[key])
      })
      let cursorChange = false
      if (this.viewFormStatus == 'addnew') {
        cursorChange = true
        this.$set(this, 'viewFormStatus', 'edit')
      }
      const {afterMove, afterSave} = this.viewFormEvents
      afterMove && afterMove(this.viewFormData, this.propInitData, this.viewFormStatus, cursorChange)
      afterSave && afterSave()
      if (this.flow && this.flowNodes.length > 0) { //如果是流程节点，刷新
        this.ocRefreshCurrentRow()
      }
      // 回调父界面事件
      this.$emit('after-save', this.viewFormStatus, this.viewFormData)
      this.lastSaveData = JSON.parse(JSON.stringify(this.viewFormData))
      setTimeout(() => {
        this.isRefreshCurrentRow = false
        this.formAutoSaveSuccess()
      }, 500)
    })
  }
}

export default dvFunPrivate
